#define _CRT_SECURE_NO_WARNINGS 1
class Solution {
    typedef long long ll;
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        vector<vector<int>> ret;

        int a = 0;
        int n = nums.size();
        sort(nums.begin(), nums.end());
        while (a < n - 3)
        {
            int b = a + 1;
            while (b < n - 2)
            {
                int left = b + 1;
                int right = nums.size() - 1;
                while (left < right)
                {
                    ll x = (ll)nums[left] + (ll)nums[right] + (ll)nums[a] + (ll)nums[b];
                    //int x=nums[left]+nums[right]+nums[a]+nums[b];;
                    if (x < target) left++;
                    else if (x > target) right--;
                    else
                    {
                        ret.push_back({ nums[left],nums[right],nums[a],nums[b] });
                        left++, right--;
                        while ((left < right) && nums[left] == nums[left - 1]) left++;
                        while ((left < right) && nums[right] == nums[right + 1]) right--;

                    }
                }
                b++;
                while ((b < n - 2) && nums[b] == nums[b - 1]) b++;
            }
            a++;
            while ((a < n - 3) && nums[a] == nums[a - 1]) a++;
        }
        return ret;
    }
};